<?php
class USERAUTH
{
    function __construct(){
        return True;
    }
    
    function login($username, $password){
        require('db.php');
        $this->username = mysql_escape_string($username);
        $this->md5_pass = md5($password);
        
        $user_query = "SELECT * FROM users WHERE 
                            `name`='{$this->username}' AND 
                            `password`='{$this->md5_pass}' 
                             LIMIT 0,1;";
        $this->res = mysql_query($user_query) or die(mysql_error()); 
        $number = mysql_num_rows($this->res);
        if($number == 0){ 
            return False; 
        } else { 
            $this->start_session(); 
            return True;
        }
    }
    
    function logout(){
        session_start();
        session_destroy();
    }

    function start_session(){
        if(!isset($this->username) OR !isset($this->md5_pass)){ exit(''); }
        session_start();
        while ($row=mysql_fetch_array($this->res)){
            $_SESSION['user'] = $row['name'];
            $_SESSION['id'] = $row['id'];
            $_SESSION['type'] = $row['type'];
            
            // ключ нужен для авторизации без логина и пароля.
            $date_today = date("m.d.y");
            $key = md5("{$_SESSION['id']}{$_SESSION['user']}{$date_today}");
            
            $query = "UPDATE  `calc`.`session` SET  `key` =  '{$key}', `date`=CURRENT_TIMESTAMP WHERE  `session`.`uid` ={$_SESSION['id']}  LIMIT 1 ;";
            mysql_query($query);
            $_SESSION['key'] = $key;
        }
    }
    
    function session_status(){
        if(!isset($_SESSION['user']) OR !isset($_SESSION['type'])){
            session_start();
            session_destroy();
            header('Location: index.php');
        }
    }
}

?>
